package edu.tjpu.share.service;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
import edu.tjpu.share.app.Fields;
import edu.tjpu.share.po.FileForDownload;
import edu.tjpu.share.po.FileForUpload;
import edu.tjpu.share.po.Server;
import edu.tjpu.share.util.FileUtil;

public class NetworkStateService extends Service {

	private boolean needDownload = false;
	private boolean needUpload = false;
	private SharedPreferences sp;
	private Editor editor;
	private String typeName;
	final static private String TAG = "NetworkStateService";
	final static public String CONNECTIVITY_CHANGE = "android.net.conn.CONNECTIVITY_CHANGE";
	final static public String SYNC_ACTION = "edu.tjpu.share.service.NetworkStateService";

	private SyncBinder mBinder = new SyncBinder();

	@Override
	public IBinder onBind(Intent intent) {
		return mBinder;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		sp = getSharedPreferences("perference", MODE_PRIVATE);
		editor = sp.edit();
		needDownload = sp.getBoolean(Fields.NEED_DOWNLOAD, false);
		needUpload = sp.getBoolean(Fields.NEED_UPLOAD, false);
		// registerReceiver(connChagRec, new IntentFilter(CONNECTIVITY_CHANGE));
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		// unregisterReceiver(connChagRec);
	}

	@Override
	public void onStart(Intent intent, int startId) {
		super.onStart(intent, startId);
		typeName = intent.getStringExtra("TypeName");
		sync();

	}

	public class SyncBinder extends Binder {
		public NetworkStateService getService() {
			return NetworkStateService.this;
		}
	}

	@SuppressWarnings("unchecked")
	public void sync() {
		java.io.File cache = NetworkStateService.this.getCacheDir();
		java.io.File cacheServerinfoFile = new java.io.File(cache,
				Fields.SERVER_INFO);
		Server serverinfo = (Server) FileUtil
				.ReadObjectFromFile(cacheServerinfoFile.getAbsolutePath());
		if (needDownload) {
			java.io.File cacheForDownFile = new java.io.File(cache,
					Fields.FOR_DOWNLOAD);
			List<FileForDownload> downWaitingList = (List<FileForDownload>) FileUtil
					.ReadObjectFromFile(cacheForDownFile.getAbsolutePath());

			Iterator<FileForDownload> iterator = downWaitingList.iterator();
			while (iterator.hasNext()) {
				FileForDownload dfile = iterator.next();
				HashMap<String, Object> mapaa = new HashMap<String, Object>();
				mapaa.put(Fields.FILE_NAME, dfile.getFname());
				mapaa.put(Fields.FILE_URL, dfile.getFurl());
				mapaa.put(Fields.STORE_URL, "/Downloads/");
				mapaa.put(Fields.SERVER_INFO, serverinfo);

				Intent intent = new Intent();
				Bundle bundle = new Bundle();
				bundle.putSerializable("values", mapaa);
				intent.putExtras(bundle);
				intent.putExtra("runningThreadNum", downWaitingList.size());
				intent.setAction(DownloadService.DOWNLOAD_ACTION);
				intent.setClass(NetworkStateService.this, DownloadService.class);
				startService(intent);
				Log.v(TAG, "Download Start!");
				if(typeName!=null&&!"".equals(typeName)){
					Toast.makeText(NetworkStateService.this, "Share检测到网络："+typeName+". 开始未完成下载", Toast.LENGTH_SHORT).show();
				}
			}
			editor.putBoolean(Fields.NEED_DOWNLOAD, false);
			editor.commit();
			stopSelf();
		} else if (needUpload) {
			java.io.File cacheForUpFile = new java.io.File(cache,Fields.FOR_UPLOAD);
			List<FileForUpload> upWaitingList = (List<FileForUpload>) FileUtil.ReadObjectFromFile(cacheForUpFile.getAbsolutePath());
			Iterator<FileForUpload> iterator = upWaitingList.iterator();
			while(iterator.hasNext()){
				FileForUpload upfile = iterator.next();
				HashMap<String, Object> map = new HashMap<String, Object>();
				map.put(Fields.SERVER_INFO, serverinfo);
				map.put(Fields.FILE_FORUPLOAD, upfile);
				map.put(Fields.WITHOUTFILE, false);
				
				Intent intent = new Intent();
				Bundle bundle = new Bundle();
				bundle.putSerializable("values", map);
				intent.putExtras(bundle);
				intent.putExtra("runningThreadNum", upWaitingList.size());
				intent.setAction(UploadService.UPLOAD_ACTION);
				intent.setClass(NetworkStateService.this, UploadService.class);
				startService(intent);
				Log.v(TAG, "Upload Start!");
				Toast.makeText(NetworkStateService.this, "Share检测到网络："+typeName+". 开始未完成上传", Toast.LENGTH_SHORT).show();
			}
			editor.putBoolean(Fields.NEED_UPLOAD, false);
			editor.commit();
			stopSelf();
		} else {
			Log.v(TAG, "No work to do!");
			stopSelf();
		}
	}

}
